package com.link.base.base.consumer.service;

import com.link.base.base.address.model.AddrPst;
import com.link.base.base.consumer.dao.mybatis.mapper.PortalAccntLineTemporaryMapper;
import com.link.base.base.consumer.model.PortalAccntLine;
import com.link.base.base.consumer.model.PortalAccntLineTemporary;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.query.ImportColumn;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import com.link.core.cllog.LCLogger;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 客户(消费者）信息导入数据验证
 * @author yipeng.zhu@hand-china.com
 * @version 1.0
 * @date: 2018/11/5 16:27
 */

@Service
public class PortalAccntLineTemporaryServiceImpl extends BasicServiceImpl<PortalAccntLineTemporary>
        implements PortalAccntLineTemporaryService {
    @Resource
    private PortalAccntLineTemporaryMapper portalAccntLineTemporaryMapper;
    @Resource
    private PortalAccntLineService portalAccntLineService;

    @Override
    public BasicMapper<PortalAccntLineTemporary> getBasicMapper() throws Exception {
        return portalAccntLineTemporaryMapper;

    }

    @Override
    public void exportExcelDelete(PortalAccntLineTemporary t) {
        portalAccntLineTemporaryMapper.exportExcelDelete(t);
    }

    @Override
    public void importExcelCheck(List<PortalAccntLineTemporary> list, QueryParams qps, String acctChannel) {
        // importNo--不导入 importCover覆盖导入s
        String option = qps.getAttr1();
        StringBuilder errormsg = new StringBuilder();
        PortalAccntLine entity = new PortalAccntLine();
        HashMap<String, String> map = new HashMap<>(16);
        PortalAccntLine record = new PortalAccntLine();
        for (int i = 0; i < list.size(); i++) {
            //Excel数据重复验证 以手机号为唯一标准
            if (map.isEmpty()) {
                map.put(list.get(i).getMobilePhone1(), String.valueOf(i));
            } else {
                if (map.containsKey(list.get(i).getMobilePhone1())) {
                    errormsg.append("导入的文件有相同的手机号,");
                } else {
                    map.put(list.get(i).getMobilePhone1(), String.valueOf(i));
                }
            }


            // 手机号格式验证
            String checkPhone = contestTest("mobilephone1", list.get(i).getMobilePhone1());
            if (StringUtils.isNotBlank(checkPhone)) {
                errormsg.append(checkPhone);
            } else {
                if ("importNo".equals(option)) {
                    // 客户来源
                    record.setAcctChannel(acctChannel);
                    record.setAcctType("ChannelConsumer");
                    record.setLoginCorpId(qps.getLoginCorpId());
                    record.setMobilePhone1(list.get(i).getMobilePhone());
                    PortalAccntLine existAccnt = portalAccntLineService.queryAccntByCombinCondition(record);
                    // 是否存在相同客户
                    if (existAccnt != null) {
                        list.get(i).setAccntValidate("N");
                        errormsg.append("系统中已有相同的手机号客户,");
                    }
                }

            }
            // 生日格式验证
            String checkBirthday = contestTest("BIRTHDAY", list.get(i).getBirthday());
            if (StringUtils.isNotBlank(checkBirthday)) {
                errormsg.append(checkBirthday + ",");
            }
            // 值列表 验证
            String checkLov = lovCheck(entity, qps, list.get(i));
            if (StringUtils.isNotBlank(checkLov)) {
                errormsg.append(checkLov + ",");
            }
            // 省市区验证
            String addrChcek = addrCheck(list.get(i), qps);
            if (StringUtils.isNotBlank(addrChcek)) {
                errormsg.append(addrChcek);
            }
            if (errormsg.length() > 0) {
                list.get(i).setValidateInfo(errormsg.toString());
                list.get(i).setAccntValidate("N");
            } else {
                list.get(i).setAccntValidate("Y");

            }
        }

    }

    /**
     * 验证省市区 是否规范
     * @author yipeng.zhu@hand-china.com
     * @param state  省
     * @param city   市
     * @param county 区
     * @return
     * @throws
     * @date 2019/3/8 9:19
     */
    @Override
    public Map<String, Object> queryAddrCheck(String state, String city, String county) {
        Map<String, Object> result = new HashMap<>(4);
        QueryParams qps = new QueryParams();
        if (state != null && state != "") {
            qps.setAttr5(state);
        }
        if (city != null && city != "") {
            qps.setAttr6(city);
        }
        if (county != null && county != "") {
            qps.setAttr7(county);
        }
        AddrPst addr = portalAccntLineTemporaryMapper.queryAddrCheck(qps);
        if (addr == null) {
            result.put("success", false);
            result.put("msg", "中国没有" + qps.getAttr5());
        } else if (addr.getParentAddr2Name() == null) {
            result.put("success", false);
            result.put("msg", qps.getAttr5() + "下没有" + qps.getAttr6());
        } else if (addr.getAddrName() == null) {
            result.put("success", false);
            result.put("msg", qps.getAttr5() + qps.getAttr6() + "下没有" + qps.getAttr7());
        } else {
            result.put("success", true);
        }
        return result;
    }

    /**
     * 验证手机号
     * @author yipeng.zhu@hand-china.com
     * @param filed 列名
     * @param value 值
     * @date 2019/3/8 9:14
     */

    public String contestTest(String filed, String value) {
        String content = null;
        String mobilephone = "mobilephone1";
        // 手机号验证
        if (mobilephone.equalsIgnoreCase(filed)) {
            String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
            int len = 11;
            if (value.length() != len) {
                content = "手机号应为11位数";
            } else {
                Pattern p = Pattern.compile(regex);
                Matcher m = p.matcher(value);
                boolean isMatch = m.matches();
                if (!isMatch) {
                    content = "手机号格式错误";
                }
            }
        }
        String birthday = "BIRTHDAY";
        if (birthday.equalsIgnoreCase(filed)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
                format.setLenient(false);
                format.parse(value);
            } catch (ParseException e) {
                LCLogger.withException(e);
                content = "请按照2007-02-29格式";
            }
        }

        return content;
    }

    /**
     * 判断单元格里的值是否在值列表中
     * @author yipeng.zhu@hand-china.com
     * @param entity 消费者信息实体类
     * @return
     * @throws
     * @date 2018/5/21
     */
    public String lovCheck(PortalAccntLine entity, QueryParams qps, PortalAccntLineTemporary acctemporary) {
        StringBuilder error = new StringBuilder();
        try {
            Class<?> clz = entity.getClass();
            // 获取类中的所有方法集合
            Method[] methods = clz.getDeclaredMethods();
            for (Method method : methods) {
                // 循环方法集合
                for (ImportColumn model : qps.getImportColumns()) {
                    if (("set" + model.getField().toLowerCase()).equals(method.getName().toLowerCase())) {
                        if (!StringUtils.isBlank(model.getLov())) {
                            String content = (String) PropertyUtils.getSimpleProperty(acctemporary, model.getField());
                            String lovcheck = getKey(model.getLovMap(), content);
                            if (StringUtils.isBlank(lovcheck)) {
                                error.append("," + model.getTitle() + "没有选取模板中的值");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            LCLogger.withException(e);
        }
        return error.toString();
    }

    /**
     * Map 根据值 取 键
     * @author yipeng.zhu@hand-china.com
     * @param map
     * @return
     * @throws
     * @date 2018/5/19
     */
    public String getKey(Map<String, String> map, String value) {
        String key = null;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (value.equals(entry.getValue())) {
                key = entry.getKey();
            }
        }
        return key;
    }

    /**
     * 导入数据 是否有省市区 有(验证)
     * @author yipeng.zhu@hand-china.com
     * @param entity 消费者信息
     * @date 2018/5/21
     */
    public String addrCheck(PortalAccntLineTemporary entity, QueryParams qps) {
        String msg = null;
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            List<ImportColumn> importColumns = qps.getImportColumns();
            for (int i = 0; i < importColumns.size(); i++) {
                if ("province".equals(importColumns.get(i).getField())) {
                    result = queryAddrCheck(entity.getProvince(), entity.getCity(), entity.getDistrict());
                    break;
                }
            }
            if (!result.isEmpty()) {
                String suc = "success";
                if (!(boolean) result.get(suc)) {
                    msg = result.get("msg").toString();
                }
            }

        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return msg;
    }

}
